package logic

import (
	"context"
	"encoding/json"
	"errors"
	"fmt"
	"gozeroStandalone/internal/model"
	"gozeroStandalone/internal/svc"
	"gozeroStandalone/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

/*
 +----------------------------------------------------------------------
 + Title        : DemoLogic
 + Author       : huwl
 + Version      : 1.0.0
 + Initial-Time : 2025-08-08
 + Last-time    : 这个文件最后修改的时间 + 修改人的名称
 + Desc         : 案例逻辑
 +----------------------------------------------------------------------
*/

type DemoLogic struct {
	BaseLogic
}

/**
 * 创建案例逻辑实例
 *
 * @param context.Context ctx ----------------------必传
 * @param *svc.ServiceContext svcCtx ---------------必传
 * @return *DemoLogic
 * @author huwl
 * @date 2025/10/14 12:54:03
 */
func NewDemoLogicInstance(ctx context.Context, svcCtx *svc.ServiceContext) *DemoLogic {
	return &DemoLogic{
		BaseLogic{
			Ctx:    ctx,
			SvcCtx: svcCtx,
			Logger: logx.WithContext(ctx),
		},
	}
}

/**
 * 新增
 *
 * @param []string Hobby ---------------------------必传
 * @param map[string]string Spec -------------------必传
 * @return error
 * @author huwl
 * @date 2025/11/22 22:15:45
 */
func (logic *DemoLogic) Add(params types.DemoAddRequest) error {
	if len(params.Hobby) <= 0 {
		return errors.New("爱好不能空")
	}
	if len(params.Spec) <= 0 {
		return errors.New("规格不能空")
	}

	// 转换为json数据
	hobby, _ := json.Marshal(params.Hobby)
	spec, _ := json.Marshal(params.Spec)
	_, err := logic.SvcCtx.DemoModel.Insert(logic.Ctx, &model.MallDemo{
		Hobby: string(hobby),
		Spec:  string(spec),
	})
	if err != nil {
		return err
	}

	return nil
}

/**
 * 编辑
 *
 * @param uint16 Id --------------------------------必传
 * @param []string Hobby ---------------------------非必传
 * @param map[string]string Spec -------------------非必传
 * @return error
 * @author huwl
 * @date 2025/11/22 22:15:45
 */
func (logic *DemoLogic) Edit(in types.DemoEditRequest) error {
	if in.Id <= 0 {
		return errors.New("id错误")
	}

	params := map[string]interface{}{}
	if len(in.Hobby) <= 0 {
		// 转换为json数据
		hobby, _ := json.Marshal(in.Hobby)
		params["hobby"] = hobby
	}
	if len(in.Spec) <= 0 {
		// 转换为json数据
		spec, _ := json.Marshal(in.Spec)
		params["spec"] = spec
	}

	err := logic.SvcCtx.DemoModel.EditByPrimaryKey(logic.Ctx, params, in.Id)
	if err != nil {
		return err
	}

	return nil
}

/**
 * 列表
 *
 * @param uint16 Id --------------------------------非必传
 * @param string Hobby -----------------------------非必传
 * @param string Spec ------------------------------非必传
 * @param string SortField -------------------------非必传
 * @param string SortType --------------------------非必传
 * @param uint8 Page -------------------------------非必传
 * @param int8 PageSize ----------------------------非必传
 * @return []map[string]interface{}, int64, error
 * @author huwl
 * @date 2025/11/22 22:23:59
 */
func (logic *DemoLogic) List(params types.DemoQueryRequest, page uint8, pageSize int8) ([]map[string]interface{}, int64, error) {
	data := map[string]interface{}{}
	if params.Id > 0 {
		data["id"] = params.Id
	}
	if params.Hobby != "" {
		data["hobby JSON_CONTAINS ?"] = fmt.Sprintf(`["%s"]`, params.Hobby)
	}
	if params.Spec != "" {
		// 查询: {"name": "zzzz", "value": "222"}
		// 使用 ->> 操作符 (MySQL 5.7.13+)
		// Where("JSON_EXTRACT(data, '$.name') = ?", "xxxx")
		data["spec->>'$.name'"] = params.Spec
	}
	if params.SortField == "" {
		params.SortField = "id"
	}
	if params.SortType == "" {
		params.SortType = "DESC"
	}

	// 获取数量
	total, err := logic.SvcCtx.DemoModel.GetResultsByTotal(logic.Ctx, data)
	if err != nil {
		return nil, 0, err
	}

	// 获取数据
	items := []map[string]interface{}{}
	if total > 0 {
		var demoes []*model.MallDemo
		err = logic.SvcCtx.DemoModel.GetResultsByParams(logic.Ctx, &demoes, data, uint32(page), pageSize, params.SortField+" "+params.SortType)
		if err != nil {
			return nil, 0, err
		}
		for _, value := range demoes {
			// 解析json数据
			var hobby []string
			json.Unmarshal([]byte(value.Hobby), &hobby)
			var spec map[string]string
			json.Unmarshal([]byte(value.Spec), &spec)

			items = append(items, map[string]interface{}{
				"id":    value.Id,
				"hobby": hobby,
				"spec":  spec,
			})
		}
	}

	return items, total, nil
}
